﻿
/*
Author: liyonghelpme
Email: 233242872@qq.com
*/

/*
Author: liyonghelpme
Email: 233242872@qq.com
*/
using Google.ProtocolBuffers;
using MyLib;

namespace KBEngine
{
	using System; 
	using System.Net; 
	
    /// <summary>
    /// 只处理报文读取
    /// </summary>
    public class MemoryStream 
    {
    	public const int BUFFER_MAX = 8192;
    	public int rpos = 0;
    	public int wpos = 0;
    	private byte[] datas_ = new byte[BUFFER_MAX]; 
        public MemoryStream()
        {
            codedInputStream = CodedInputStream.CreateInstance(datas_, 0, datas_.Length);
        }
        public void Reset()
        {
            rpos = 0;
            wpos = 0;
        }
		

    	public byte[] data()
    	{
    		return datas_;
    	}
		
		public void setData(byte[] data)
		{
			datas_ = data;
		}
		
		//---------------------------------------------------------------------------------
		public SByte readInt8()
		{
			return (SByte)datas_[rpos++];
		}
	
		public Int16 readInt16()
		{
			rpos += 2;
			var ret = BitConverter.ToInt16(datas_, rpos - 2);
			return IPAddress.NetworkToHostOrder (ret);
		}
			
		
		public Byte readUint8()
		{
			return datas_[rpos++];
		}
	    /// <summary>
        /// 小端 pb兼容
        /// </summary>
        /// <returns></returns>
		public UInt16 readUint16()
		{
            return (UInt16)((readUint8()) | (readUint8() << 8));
		}

		
		public void writeInt8(SByte v)
		{
			datas_[wpos++] = (Byte)v;
		}
	
		public void writeUint8(Byte v)
		{
			datas_[wpos++] = v;
		}
	
	
		public void readSkip(UInt32 v)
		{
			rpos += (int)v;
		}
		
		//---------------------------------------------------------------------------------
		public UInt32 fillfree()
		{
			return (UInt32)(BUFFER_MAX - wpos);
		}
	
		//---------------------------------------------------------------------------------
		public UInt32 opsize()
		{
			return (UInt32)(wpos - rpos);
		}
	
		//---------------------------------------------------------------------------------
		public bool readEOF()
		{
			return (BUFFER_MAX - rpos) <= 0;
		}
		
		//---------------------------------------------------------------------------------
		public UInt32 totalsize()
		{
			return opsize();
		}
	
		//---------------------------------------------------------------------------------
		public void opfini()
		{
			rpos = wpos;
		}
		
		//---------------------------------------------------------------------------------
		public void clear()
		{
			rpos = wpos = 0;
		}
		
	
        private CodedInputStream codedInputStream;
        public CodedInputStream GetInputStream()
        {
            //return CodedInputStream.CreateInstance(datas_, rpos, (int)opsize());
            codedInputStream.bufferPos = rpos;
            codedInputStream.bufferSize = (int)opsize();
            return codedInputStream;
        }
	
    }
    
} 
